package com.comita.selenium.applogic;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.comita.selenium.model.User;



public class UserHelper extends DriverBasedHelper {
	private ApplicationManager manager;
	private boolean acceptNextAlert = true;
	
	public UserHelper(ApplicationManager manager) {
	    super(manager.getWebDriver());
	    this.manager = manager;
	}	
	
	public void loginAs(User user){		
		driver.get(manager.baseUrl + "php4dvd/");		
	    wait.until(ExpectedConditions.elementToBeClickable(By.id("username")));
	    driver.findElement(By.id("username")).clear();
	    driver.findElement(By.id("username")).sendKeys("admin");    
	    driver.findElement(By.name("password")).clear();
	    driver.findElement(By.name("password")).sendKeys("admin");
	    wait.until(ExpectedConditions.elementToBeClickable(By.name("submit")));
	    driver.findElement(By.name("submit")).click();	   
	}
	
	public void logout(){
		driver.get(manager.baseUrl + "php4dvd/");
		wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Log out")));
	    driver.findElement(By.linkText("Log out")).click();
	    closeAlert();
	}
	
	private boolean isElementPresent(By by) {
	    try {
	      WebDriverWait wait = new WebDriverWait(driver, 5);
	      wait.until(ExpectedConditions.elementToBeClickable(by));	      
	      return true;
	    } catch (TimeoutException e) {
	      return false;
	    }
	  }
	
	public boolean isLoggedIn(){
		driver.get(manager.baseUrl + "php4dvd/");		
		return isElementPresent(By.linkText("Log out"));
	}
	
	private void closeAlert() {
	    try {
	      Alert alert = driver.switchTo().alert();	      
	      if (acceptNextAlert) {
	        alert.accept();
	      } else {
	        alert.dismiss();
	      }	      
	    } finally {
	      acceptNextAlert = true;
	    }
	  }
	
}
